package org.bbs.demo.concern.api;


import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.concern.dao.AddConcernDao;
import org.bbs.demo.concern.dao.DeleteConcernDao;
import org.bbs.demo.concern.dto.ConcernDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/concern")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class DeleteConcernApi {
    @Autowired
    private DeleteConcernDao deleteconcerndao;

    @PostMapping("/delete")
    public Result info(@RequestBody ConcernDto concerndto, @RequestHeader String Token){
        try{
            String followId = JWTutil.getUserID(Token);
            concerndto.setFollow_id(followId);
            String userId = concerndto.getUser_id();
            if (deleteconcerndao.findUser(userId) == null || deleteconcerndao.findUser(followId) == null){
                throw new BusinessException("用户id不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"用户id不存在");
            }
            if (deleteconcerndao.findConcern(concerndto) == null){
                throw new BusinessException("用户未关注");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"用户未关注");
            }
            deleteconcerndao.deleteConcern(concerndto);
            return Result.OK("取消关注成功");
        }catch (DuplicateKeyException err) {
            throw new BusinessException("删除失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "删除失败");
        }
    }
}
